<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\BindMobileRequest;
use App\Http\Requests\DecryptDataRequest;
use App\Http\Requests\FormIdRequest;
use App\Http\Resources\ProjectCollection;
use App\Http\Resources\UserCollection;
use App\Http\Resources\UserResource;
use App\model\Coustomer;
use App\model\Project;
use App\model\UserFormId;
use App\model\Xiaofei;
use App\Repository\WechatRepository;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;

class UserController extends Controller
{
    public function record(Request $request){

        $today=Coustomer::where('user_id',\Auth::user()->id)
        ->select(\DB::raw('count(customer_id) as num'),'project_id')
            ->whereDate('created_at',Carbon::yesterday())
            ->groupBy(['project_id'])
            ->pluck('num','project_id');
        $week=Coustomer::where('user_id',\Auth::user()->id)->select(\DB::raw('count(customer_id) as num'),'project_id')
            ->whereDate('created_at',Carbon::yesterday())
            ->groupBy(['project_id'])
            ->pluck('num','project_id');
        $mouth=Coustomer::where('user_id',\Auth::user()->id)->select(\DB::raw('count(customer_id) as num'),'project_id')
            ->whereBetween('created_at',[ Carbon::now()->firstOfMonth(),Carbon::now()->lastOfMonth()])
            ->groupBy(['project_id'])
            ->pluck('num','project_id');
        $total=Coustomer::where('user_id',\Auth::user()->id)->select(\DB::raw('count(customer_id) as num'),'project_id')
            ->groupBy(['project_id'])
            ->pluck('num','project_id');

        $user=User::find($request->user()->id);
        if(  $user->hasPermissionTo('all')){
            $project= Project::all();
        }else{
            $project=Project::whereIn('project_id',$user->project_id)->get();
        }
        $Completed=Coustomer::select('project_id',\DB::raw('count(customer_id) as num'))
            ->where('user_id',\Auth::user()->id)
            ->where('status',Coustomer::Completed)
            ->groupBy('project_id')
            ->pluck('num','project_id');
        $follow_up=Coustomer::select('project_id',\DB::raw('count(customer_id) as num'))
            ->where('user_id',\Auth::user()->id)
            ->where('status',Coustomer::Follow_up)
            ->groupBy('project_id')
            ->pluck('num','project_id');
        $No_Intention=Coustomer::select('project_id',\DB::raw('count(customer_id) as num'))
            ->where('user_id',\Auth::user()->id)
            ->where('follow_status',Coustomer::Unintentional)
            ->groupBy('project_id')
            ->pluck('num','project_id');
        $Have_visited=
            Coustomer::select('project_id',\DB::raw('count(customer_id) as num'))
                ->where('user_id',\Auth::user()->id)
                ->where('follow_status',Coustomer::To_Be_Follow_up)
                ->groupBy('project_id')
                ->pluck('num','project_id');
     /*   $Have_Intention= Coustomer::select('project_id',\DB::raw('count(id) as num'))
            ->where('user_id',\Auth::user()->id)
            ->where('follow_status',Coustomer::To_Be_Follow_up)
            ->groupBy('project_id')
            ->get();*/
        $projet=$project->map(function ($value)use($today,$mouth,$week,$total,$Completed,$No_Intention,$Have_visited,$follow_up){
         return    [
             'id'=>$value->project_id,
              'name'=>$value->name,
             'image'=>$value->image=='' ? config('app.url').'/image/default.png':Storage::url($value->image),
              'today'=>$today->get($value->project_id,0) ?? 0,
              'week'=>$week->get($value->project_id,0) ?? 0,
               'mouth'=>$mouth->get($value->project_id,0) ?? 0,
                'total'=>$total->get($value->project_id,0) ?? 0,
                'Have_visited'=>$Have_visited->get($value->project_id,0) ?? 0,
               //  'No_Visit'=>0,
                'Have_Intention'=>0,
                'No_Intention'=>$No_Intention->get($value->project_id,0) ?? 0,
                'Completed'=>$Completed->get($value->project_id,0) ?? 0,
                'Follow_up'=>$follow_up->get($value->project_id,0) ?? 0,
            ];

      });
        return new ProjectCollection($projet);
    }

    /**
     * 项目经理页面
     * @param Request $request
     * @return ProjectCollection
     */
    public function record3(Request $request){

        $today=Coustomer::select(\DB::raw('count(customer_id) as num'),'project_id')
            ->whereDate('created_at',Carbon::yesterday())
            ->groupBy(['project_id'])
            ->pluck('num','project_id');
        $week=Coustomer::select(\DB::raw('count(customer_id) as num'),'project_id')
            ->whereDate('created_at',Carbon::yesterday())
            ->groupBy(['project_id'])
            ->pluck('num','project_id');
        $mouth=Coustomer::select(\DB::raw('count(customer_id) as num'),'project_id')
            ->whereBetween('created_at',[ Carbon::now()->firstOfMonth(),Carbon::now()->lastOfMonth()])
            ->groupBy(['project_id'])
            ->pluck('num','project_id');
        $total=Coustomer::select(\DB::raw('count(customer_id) as num'),'project_id')
            ->groupBy(['project_id'])
            ->pluck('num','project_id');
        $user=User::find($request->user()->id);
        if(  $user->hasPermissionTo('all')){
            $project= Project::all();
        }else{
            $project=Project::whereIn('project_id',$user->project_id)->get();
        }
        $Completed=Coustomer::select('project_id',\DB::raw('count(customer_id) as num'))
            ->where('status',Coustomer::Completed)
            ->groupBy('project_id')
            ->pluck('num','project_id');
        $follow_up=Coustomer::select('project_id',\DB::raw('count(customer_id) as num'))
            ->where('status',Coustomer::Follow_up)
            ->groupBy('project_id')
            ->pluck('num','project_id');
        $No_Intention=Coustomer::select('project_id',\DB::raw('count(customer_id) as num'))
            ->where('follow_status',Coustomer::Unintentional)
            ->groupBy('project_id')
            ->pluck('num','project_id');
        $Have_visited=
            Coustomer::select('project_id',\DB::raw('count(customer_id) as num'))
                ->where('follow_status',Coustomer::To_Be_Follow_up)
                ->groupBy('project_id')
                ->pluck('num','project_id');
        /*   $Have_Intention= Coustomer::select('project_id',\DB::raw('count(id) as num'))
               ->where('user_id',\Auth::user()->id)
               ->where('follow_status',Coustomer::To_Be_Follow_up)
               ->groupBy('project_id')
               ->get();*/
        $projet=$project->map(function ($value)use($today,$mouth,$week,$total,$Completed,$No_Intention,$Have_visited,$follow_up){
            return    [
                'id'=>$value->project_id,
                'name'=>$value->name,
                'image'=>$value->image=='' ? config('app.url').'/image/default.png':Storage::url($value->image),
                'today'=>$today->get($value->project_id,0) ?? 0,
                'week'=>$week->get($value->project_id,0) ?? 0,
                'mouth'=>$mouth->get($value->project_id,0) ?? 0,
                'total'=>$total->get($value->project_id,0) ?? 0,
                'Have_visited'=>$Have_visited->get($value->project_id,0) ?? 0,
                //  'No_Visit'=>0,
                'Have_Intention'=>0,
                'No_Intention'=>$No_Intention->get($value->project_id,0) ?? 0,
                'Completed'=>$Completed->get($value->project_id,0) ?? 0,
                'Follow_up'=>$follow_up->get($value->project_id,0) ?? 0,
            ];

        });
        return new ProjectCollection($projet);
    }
    /**
     * 总经理首页
     */
    public function recordV2(Request $request){
        $user=User::find($request->user()->id);


        $today=Coustomer::select(\DB::raw('count(customer_id) as num'),'project_id')
            ->whereDate('created_at',Carbon::yesterday())
            ->groupBy(['project_id'])
            ->pluck('num','project_id');
        $week=Coustomer::select(\DB::raw('count(customer_id) as num'),'project_id')
            ->whereBetween('created_at',[Carbon::today()->addDays(-(Carbon::getWeekendDays())['0']+1),Carbon::today()->addDays((Carbon::getWeekendDays())['1']+2)])
            ->groupBy(['project_id'])
            ->pluck('num','project_id');
        $mouth=Coustomer::select(\DB::raw('count(customer_id) as num'),'project_id')
            ->whereBetween('created_at',[ Carbon::now()->firstOfMonth(),Carbon::now()->lastOfMonth()])
            ->groupBy(['project_id'])
            ->pluck('num','project_id');
        $total=Coustomer::select(\DB::raw('count(customer_id) as num'),'project_id')
            ->groupBy(['project_id'])
            ->pluck('num','project_id');
        $yesterday_money=Xiaofei::select(\DB::raw('sum(xiaofei) as num'),'project_id')
            ->whereDate('created_at','>=',Carbon::yesterday())
            ->whereDate('created_at','<',Carbon::today())
            ->groupBy(['project_id'])
            ->pluck('num','project_id');

        $week_money=Xiaofei::select(\DB::raw('sum(xiaofei) as num'),'project_id')
            ->whereBetween('created_at',[Carbon::today()->addDays(-(Carbon::getWeekendDays())['0']+1),Carbon::today()->addDays((Carbon::getWeekendDays())['1']+2)])
            ->groupBy(['project_id'])
            ->pluck('num','project_id');
        $mouth_money=Xiaofei::select(\DB::raw('sum(xiaofei) as num'),'project_id')
            ->whereBetween('created_at',[ Carbon::now()->firstOfMonth(),Carbon::now()->lastOfMonth()])
            ->groupBy(['project_id'])
            ->pluck('num','project_id');
        $total_money=Xiaofei::select(\DB::raw('sum(xiaofei) as num'),'project_id')
            ->groupBy(['project_id'])
            ->pluck('num','project_id');


        if(  $user->hasPermissionTo('all')){
            $project= Project::all();

        }else{

            $project=Project::whereIn('project_id',$user->project_id)->get();
        }

        $projet=$project->map(function ($value)use($today,$mouth,$week,$total,$yesterday_money,$week_money,$mouth_money,$total_money){
            return    [
                'id'=>$value->project_id,
                'name'=>$value->name,
                'image'=>$value->image=='' ? config('app.url').'/image/default.png':Storage::url($value->image),
                'yesterday'=>$today->get($value->project_id,0) ?? 0,
                'week'=>$week->get($value->project_id,0) ?? 0,
                'mouth'=>$mouth->get($value->project_id,0) ?? 0,
                'total'=>$total->get($value->project_id,0) ?? 0,
                'yesterday_money'=>$yesterday_money->get($value->project_id,0) ?? 0,
                'week_money'=>$week_money->get($value->project_id,0) ?? 0,
                'mouth_money'=>$mouth_money->get($value->project_id,0) ?? 0,
                'total_money'=>$total_money->get($value->project_id,0) ?? 0,
            ];

        });
        return new ProjectCollection($projet);
    }
    public function list1(Request $request){

        $user=User::find($request->user()->id);

        if (!empty($user->project_id)){
            $users=User::join('user_info','users.id','=','user_info.user_id');
            foreach ($user->project_id as $k=>$project){
                if ($k==0){
                    $users=$users->whereRaw("find_in_set(?,project_id)",[$project]);
                }else{
                    $users=$users->orWhereRaw("find_in_set(?,project_id)",[$project]);
                }
            }
            $users=$users->get();
        }
        if ($user->checkPermissionTo('all')){
            $users=User::join('user_info','users.id','=','user_info.user_id')->get();
        }

        return new UserCollection($users);
    }
    /**
     * 业务员列表根据不同项目筛选
     * @authenticated
     */
    public function list(Request $request){
        $array=[];
        $user=User::find($request->user()->id);
        $customer_id=$request->customer_id;
        if ($customer_id){
            $users=User::join('user_info','users.id','=','user_info.user_id');
            $customer=Coustomer::find($customer_id);
            $users=$users->whereRaw("find_in_set(?,project_id)",[$customer->project_id]);
            $users=$users->get()->groupBy('groupName')->toArray();
        }else{
            if (!empty($user->project_id)){
                $users=User::join('user_info','users.id','=','user_info.user_id');
                foreach ($user->project_id as $k=>$project){
                    if ($k==0){
                        $users=$users->whereRaw("find_in_set(?,project_id)",[$project]);
                    }else{
                        $users=$users->orWhereRaw("find_in_set(?,project_id)",[$project]);
                    }
                }
                $users=$users->get()->groupBy('groupName')->toArray();
            }
        }

        if ($user->checkPermissionTo('all')){
            $users=User::join('user_info','users.id','=','user_info.user_id')->get()->groupBy('groupName')->toArray();
        }
        foreach ($users as $k=>$value){
            $array[]=['groupName'=>$k,'users'=>$value];
        }
        return new UserCollection(collect($array));
    }
    public function bindMobile(BindMobileRequest $request){
            $user=User::find(\Auth::guard('api')->id());


                $user->mobile=$request->mobile;
                $user->save();

            return response()->json([
                'code'=>1,
                'message'=>'绑定手机成功'
            ]);
    }
    /**
     * 用户信息
     * @group 业务员管理
     *
     *
     */

    public function index(Request $request){
            $user=User::find(\Auth::guard('api')->id());
            return new UserResource($user);
    }
    //收集formId
    public function formCreate(FormIdRequest $request){
        $formId=new UserFormId();
        $formId->user_id=\Auth::guard('api')->id();
        $formId->form_id=$request->form_id;
        $formId->save();
        return  response()->json([
            'code'=>1,
            'message'=>'success'
        ]);
    }
    //解密
    public function decryptData(DecryptDataRequest $request,WechatRepository $repository){
       \Log::error('解密:'.$request->user()->id,$request->all());
       \Log::error($request->user()->session_key);
        $result=$repository->decryptData($request->user()->session_key,
                $request->get('iv'),
                $request->get('encryptData')
            );
        return $result;
    }
    public function unionid(Request $request){
        //dd(11);
        $user=User::find(\Auth::guard('api')->id());
        if ($user->unionid==null){
            $user->unionid=$request->unionid;
            $user->save();
        }

      //  dd($user);

        return  response()->json([
            'code'=>1,
            'message'=>'success'
        ]);

    }
}
